﻿using ResxHelper.Logic;
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using ResxHelper.Object;

namespace ResxHelper.Forms
{
    public partial class FrmMerge : Form
    {
        private ResourceFile _originalResx;
        private ResourceFile _importedResx;
        private ResourceFile _mergedResx;
        private MergeOption _mergeOption = MergeOption.Full;

        public event FileChangedEventHandler FileChanged;

        public FrmMerge()
        {
            InitializeComponent();
            FileChanged += OnFileChanged;
            InitializeControls();
        }

        private void InitializeControls()
        {
            InitializeGrid(dgOriginal);
            InitializeGrid(dgImported);
            InitializeGrid(dgMerged);
            InitializeMergeOptions();
        }

        private static void InitializeGrid(DataGridView dgPreview)
        {
            dgPreview.AutoGenerateColumns = false;
            dgPreview.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dgPreview.RowHeadersVisible = false;
            var cell = new DataGridViewTextBoxCell();
            var key = new DataGridViewTextBoxColumn
            {
                CellTemplate = cell,
                Name = "Key",
                HeaderText = "Key",
                DataPropertyName = "Key"
            };
            var value = new DataGridViewTextBoxColumn
            {
                CellTemplate = cell,
                Name = "Value",
                HeaderText = "Value",
                DataPropertyName = "Value"
            };
            var comment = new DataGridViewTextBoxColumn
            {
                CellTemplate = cell,
                Name = "Comment",
                HeaderText = "Comment",
                DataPropertyName = "Comment"
            };
            dgPreview.Columns.AddRange(new DataGridViewColumn[] { key, value, comment });
        }

        private void InitializeMergeOptions()
        {
            cboMergeOption.DataSource = Enum.GetValues(typeof (MergeOption));
            cboMergeOption.SelectedItem = MergeOption.Full;
        }

        #region -- Events --
        private void btnLoadOriginal_Click(object sender, EventArgs e)
        {
            var path = DialogHelper.PromptForFile(ApplicationConstants.SaveTypesAllFilter);
            _originalResx = ResourceFile.Open(path);
            if (_originalResx != null) LoadGridData(_originalResx, dgOriginal);

            OnFileChanged(this, new ResourceFileChangedEventArgs(_originalResx));
        }

        private void btnLoadImport_Click(object sender, EventArgs e)
        {
            var path = DialogHelper.PromptForFile(ApplicationConstants.SaveTypesAllFilter);
            _importedResx = ResourceFile.Open(path);

            if (_importedResx != null) LoadGridData(_importedResx, dgImported);
            OnFileChanged(this, new ResourceFileChangedEventArgs(_importedResx));
        }

        public void OnFileChanged(object sender, ResourceFileChangedEventArgs e)
        {
            if (FileChanged == null) return;

            if (_originalResx != null && _importedResx != null) DoMerge();
        }

        private void cboMergeOption_SelectedIndexChanged(object sender, EventArgs e)
        {
            var cbo = (ComboBox)sender;
            if (cbo.SelectedValue is MergeOption)
            {
                _mergeOption = (MergeOption)cbo.SelectedValue;
                FileChanged(this, ResourceFileChangedEventArgs.Empty);
            }
        }

        private void btnSaveMerge_Click(object sender, EventArgs e)
        {
            if (_mergedResx == null)
            {
                MessageBox.Show("No merged document was loaded!", "Nothing to save", MessageBoxButtons.OK);
            }

            DialogResult result;
            var path = DialogHelper.GetSaveFileLocation(ApplicationConstants.SaveTypesAllFilter, out result);
            if(result != DialogResult.OK) return;
            
            FileHelper.SaveAs(_mergedResx, path);

            if (chkKeepOpen.Checked) return;

            Hide();
            Close();
        }
        #endregion

        #region -- Actions --

        private static void LoadGridData(ResourceFile resourceFile, DataGridView loadTo)
        {
            if (resourceFile.Entries == null || resourceFile.Entries.Count < 1) return;
            var entries = resourceFile.Entries;
            var listEntries = entries.Select(entry => entry.Value).ToList();
            var list = new BindingList<ResourceFileEntry>(listEntries);
            loadTo.DataSource = list;
        }

        private void DoMerge()
        {
            _mergedResx = MergeFacade.Merge(_originalResx, _importedResx, _mergeOption);
            LoadGridData(_mergedResx, dgMerged);
        }
        #endregion
    }
}
